package com.cloudcc.cloudframe.net.async;

import org.apache.http.Header;

import android.text.TextUtils;

import com.cloudcc.cloudframe.bus.AgainLoginEvent;
import com.cloudcc.cloudframe.bus.DataEvent;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.ResultCallBack;
import com.cloudcc.cloudframe.net.ServerStatusCode;
import com.cloudcc.cloudframe.net.model.BaseNetModel;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.NumberUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.loopj.android.http.TextHttpResponseHandler;

/** 
* @Description: TODO() 
* @author wangzhiqiang
* @date 2015-11-25 下午1:30:32 
* 
* @param <T> 
*/
@Deprecated
public class GsonHttpResponseHandler<T> extends TextHttpResponseHandler
		implements ResultCallBack<T>, ServerStatusCode {
	public static final String TAG = "netWork";

	protected final Class<T> mClass;
	protected final DataEvent<T> mEvent;// 事件

	public GsonHttpResponseHandler(Class<T> mClass, DataEvent<T> mEvent) {
		super();
		this.mClass = mClass;
		this.mEvent = mEvent;
	}
	
	@Override
	public void onFailure(int statusCode, Header[] headers,
			String responseString, Throwable throwable) {
		if (throwable!=null&&StringUtils.isNotBlank(throwable.getMessage())) {
			LogUtils.e("net", throwable.getMessage());
		}
		onFailure(new ErrorInfo(10005, "服务器连接出错，请检查网络!"));
	}

	@Override
	public void onSuccess(int statusCode, Header[] headers,
			String responseString) {

		LogUtils.d("net", "请求:"+getRequestURI()+"::");
		
		if (TextUtils.isEmpty(responseString)) {
			onFailure(new ErrorInfo(10002, "返回数据为空！"));
			return;
		}
		LogUtils.d("net", "网络请求数据" + responseString);
		try {
			T t = new Gson().fromJson(responseString, mClass);
			BaseNetModel b = (BaseNetModel) t;
			int retrunCode = NumberUtils.toInt(b.returnCode, -1000);

			if (b.result && retrunCode == SUCCESS_OK) {
				onSuccess(t);
			} else {// 请求失败
				if (retrunCode == -2) {// 登录失败 重新登录
					onLoginInvalid();
				} else {
					onFailure(new ErrorInfo(retrunCode, "网络通信失败..."));
				}
			}
		} catch (JsonSyntaxException e) {
			onFailure(new ErrorInfo(10003, "解析失败"));
		}catch (Exception e){
			onFailure(new ErrorInfo(10003, "数据加载出现问题"));
		}

	}

	@Override
	public void onSuccess(T t) {
		mEvent.setOk(true);
		mEvent.setData(t);
		EventEngine.post(mEvent);
	}

	@Override
	public void onFailure(ErrorInfo error) {
		mEvent.setOk(false);
		mEvent.setMessage(error.getErrorMessage());
		EventEngine.post(mEvent);
	}

	/**
	 * 登录session 的时候调用
	 */
	public void onLoginInvalid() {
		AgainLoginEvent loginEvent = new AgainLoginEvent();
		EventEngine.post(loginEvent);
		
		
	}

}
